package cn.wit.summit.chwan.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.FindFragmentAdapter;
import cn.wit.summit.chwan.adapters.FindFragmentSkeletonAdapter;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.dto.IntentDataBean;
import cn.wit.summit.chwan.models.dto.JumpBaseBean;
import cn.wit.summit.chwan.models.dto.ViewBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.event.EnergyEvent;
import cn.wit.summit.chwan.models.request.TopicListRequest;
import cn.wit.summit.chwan.models.response.DiscoveryIndexResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.net.BuildRequestUtils;
import cn.wit.summit.chwan.net.NetCallBack;
import cn.wit.summit.chwan.net.okhttplib.NetConfigStr;
import cn.wit.summit.chwan.net.okhttplib.OkHttpUtil;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStroke;
import cn.wit.summit.chwan.widgets.ItemListView;
import cn.wit.summit.chwan.widgets.RecommendTopDownloadV2View;
import cn.wit.summit.chwan.widgets.RecommendTopWalletV2View;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.skeleton.Skeleton;
import cn.wit.summit.chwan.widgets.skeleton.SkeletonScreen;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/4/11.
 */

public class FindFragment extends BaseFragment {
    private String TAG = "FindFragmen";

    @Bind(R.id.bar_title_tx)
    TextView           barTitleTx;
    @Bind(R.id.recyclerView)
    RecyclerView       recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.back)
    ImageView          back;
    @Bind(R.id.notNetFl)
    FrameLayout        notNetFl;
    private FindFragmentAdapter adapter;
    private List<ViewBean>      datas;
    private List<String> gameList = new ArrayList<>();

    Context           context;
    GridLayoutManager layoutManager;

    SparseArray<DiscoveryType> discoveryTypes;
    private final int spanCount = 5;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_find, null);
        ButterKnife.bind(this, view);
        context = getActivity();
        initApi();
        initEnergyDownloadView();
        initDiscoveryTypes();
        initView();
        //触发自动刷新
        onRefresh();

        initSkeleton();
        back.setVisibility(View.GONE);
        initViewsData();
        EventBus.getDefault().register(this);

        return view;
    }

    //region initEnergyDownloadView

    @Bind(R.id.recommendTopWallet)
    RecommendTopWalletV2View recommendTopWallet;
    @Bind(R.id.recommendTopDownload)
    RecommendTopDownloadV2View recommendTopDownload;

    protected void initEnergyDownloadView() {
        recommendTopWallet.initTotalWalletNum();
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.e(TAG + " onResume()");
        changeTopStatus();
        changeLoginStatus();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        changeTopStatus();
        changeLoginStatus();
        LogUtils.e(TAG + " onHiddenChanged():" + hidden);
    }

    private void changeTopStatus() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (recommendTopDownload != null) {
                    recommendTopDownload.setTotalDownloadNum();
                }
            }
        }, 200);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {

        String str = adapter.getPoByGameId(downloadEvent.getGameId());
        if (!StringUtils.isEmpty(str)) {
            GameListBaseBean bean = adapter.getBeanData(Integer.valueOf(str), 0);
            if (bean == null) return;
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }

            View         view     = layoutManager.findViewByPosition(Integer.valueOf(str));
            ItemListView itemView = view.findViewById(R.id.listItem);
            if (itemView == null) {
                return;
            }
            DownloadViewStroke dowView = itemView.getDownView();
            dowView.updateButn(table);
        }

        if (recommendTopDownload != null) {
            recommendTopDownload.setTotalDownloadNum();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EnergyEvent energyEvent) {
        if (recommendTopWallet != null) {
            recommendTopWallet.initTotalWalletNum();
        }
    }
    //endregion

    @OnClick(R.id.back)
    void back() {
        LogUtils.e(TAG + " back");

        IntentDataBean bean = new IntentDataBean();
        bean.setJump_link_type(3);
        bean.setJump_type(2);
        IntentUtil.getInstance().intentTo(getActivity(), bean);
    }


    //region SkeletonScreen
    SkeletonScreen skeletonScreen;

    void initSkeleton() {
        for (int i = 0; i < discoveryTypes.size(); i++) {
            datas.add(new ViewBean(FindFragmentAdapter.T_GAME_TYPE, null));
        }
        datas.add(new ViewBean(FindFragmentAdapter.T_TITLE, null));
        for (int i = 0; i < 5; i++) {
            datas.add(new ViewBean(FindFragmentAdapter.T_GAME_ITEM, null));
        }
        FindFragmentSkeletonAdapter skeletonAdapter = new FindFragmentSkeletonAdapter(getActivity(), datas);

        skeletonScreen = Skeleton.bind(recyclerView)
                .adapter(adapter)
                .adapter(skeletonAdapter)
                .shimmer(true)
                .color(R.color.shimmer_color)
                .angle(20)
                .duration(1200)
                .show();
    }

    void hideSkeleton() {
        if (skeletonScreen == null) return;
        skeletonScreen.hide();
    }

    void showSkeleton() {
        if (skeletonScreen == null) return;
        skeletonScreen.show();
    }
    //endregion

    void initDiscoveryTypes() {
        if (discoveryTypes == null) {
            discoveryTypes = new SparseArray<>();
        }

//     * '3' => '破解专题',
//     * '4' => '网游专题',
//     * '5' => '中文汉化专题',
//     * '6' => '大型游戏专题',
//     * '7' => '苹果专区专题',
//     * '8' => '谷歌专区专题',
//     * '9' => '总专题',
//     * '10' => '游戏分类',
        int i = 0;
        discoveryTypes.append(i++, new DiscoveryType(1, R.drawable.pojie, "破解"));
        discoveryTypes.append(i++, new DiscoveryType(2, R.drawable.wangyou, "网游"));
        discoveryTypes.append(i++, new DiscoveryType(3, R.drawable.zhongwenhuanhua, "中文汉化"));
        discoveryTypes.append(i++, new DiscoveryType(4, R.drawable.daxingyouxi, "大型游戏"));
        discoveryTypes.append(i++, new DiscoveryType(5, R.drawable.iphone, "苹果专区"));
        discoveryTypes.append(i++, new DiscoveryType(6, R.drawable.googlezhuanqu, "谷歌专区"));
//        discoveryTypes.append(i++, new DiscoveryType(7, R.drawable.zhuanqu, "专区"));i++;
//        discoveryTypes.append(i++, new DiscoveryType(8, R.drawable.fenlei, "分类"));i++;
        discoveryTypes.append(i++, new DiscoveryType(10, R.drawable.nvxing, "女性"));
        discoveryTypes.append(i++, new DiscoveryType(11, R.drawable.xiuxian, "休闲"));
        discoveryTypes.append(i++, new DiscoveryType(9, R.drawable.qipai, "棋牌游戏"));
        discoveryTypes.append(i++, new DiscoveryType(12, R.drawable.erciyuan, "二次元"));
        if (discoveryTypes.size() % spanCount != 0) {
            int holder = spanCount - (discoveryTypes.size() % spanCount);
            while (holder > 0) {
                discoveryTypes.append(i++, new DiscoveryType(-1, R.drawable.main_normal_icon, ""));
                holder--;
            }
        }
    }

    void addGameTypes() {
        for (int i = 0; i < discoveryTypes.size(); i++) {
            datas.add(new ViewBean(FindFragmentAdapter.T_GAME_TYPE,
                    discoveryTypes.get(i)));
        }
    }

    private void initView() {
        LogUtils.e(TAG + " initView()");

        datas = new ArrayList<>();
        adapter = new FindFragmentAdapter(getActivity(), datas, gameList);
        layoutManager = new GridLayoutManager(context, spanCount);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position < discoveryTypes.size()) return 1;
                return spanCount;
            }
        });
        recyclerView.setLayoutManager(layoutManager);

        recyclerView.setAdapter(adapter);
        recyclerView.setFocusable(false);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                FindFragment.this.onRefresh();
            }
        });
        refreshLayout.setOnLoadMoreListener(new cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                FindFragment.this.onLoadMore();
            }
        });

        adapter.clearDownloadStatus();
        adapter.notifyDataSetChanged();
    }

    //region loadSvr
    int pn = 1, pc = 20;
    int firstCached = 0;

    void loadSvr() {
        TopicListRequest request = retrofitManager.getDiscoverIndexRequest(pn, pc);
        api.getDiscoverIndex(request).enqueue(new MyCallback<ResponseBase<List<DiscoveryIndexResponse>>>() {
            @Override
            public void onSuccess(ResponseBase<List<DiscoveryIndexResponse>> model) {
                if (model != null) {
                    if (model.getCode() == 600)
                        onResponse(model.getData_info());
                    else
                        onFailure(model.getCode(), model.getMsg());
                } else {
                    onFailure(-1, "服务器数据为空！");
                }

            }

            @Override
            public void onFailure(int code, String msg) {
                onFailure(new Exception(msg), code);
            }

            public void onResponse(List<DiscoveryIndexResponse> data) {
                if (pn == 1) {
                    PreferenceUtil.savePreference(context, "discoverIndex", new Gson().toJson(data));
                    datas.clear();
                    gameList.clear();
                    addGameTypes();
                }
                addViewDatas(data);
                if (isNull(data)) {
                    stopLoading(true);
                } else {
                    pn++;
                    stopLoading();
                }

            }

            public void onFailure(Exception e, int code) {
                if (pn == 1 && firstCached == 0) {
                    initViewsData();
                    networkFailed();
                }
                stopLoading();
                if (isAdded() && !TextUtils.isEmpty(e.getMessage()))
                    showToast(e.getMessage());
            }
        });
    }

    void loadSvr1() {
        OkHttpUtil.getDefault(context).doPostAsync(BuildRequestUtils.getInstance(context).getDiscoverIndex(pn, pc)
                , new NetCallBack<>(context, DiscoveryIndexResponse.class, new NetCallBack.Back<List<DiscoveryIndexResponse>>() {//ResponseBase<List<TopAdBean>>

                    @Override
                    public void onCache(List<DiscoveryIndexResponse> data) {
                        if (pn == 1) {
                            datas.clear();
                            gameList.clear();
                            addGameTypes();
                            addViewDatas(data);
                            adapter.clearDownloadStatus();
                            adapter.notifyDataSetChanged();
                            firstCached = 1;
                        }
                    }

                    @Override
                    public void onResponse(List<DiscoveryIndexResponse> data) {
                        if (pn == 1) {
                            PreferenceUtil.savePreference(context, "discoverIndex", new Gson().toJson(data));
                            datas.clear();
                            gameList.clear();
                            addGameTypes();
                        }
                        addViewDatas(data);
                        if (isNull(data)) {
                            stopLoading(true);
                        } else {
                            pn++;
                            stopLoading();
                        }

                    }

                    @Override
                    public void onFailure(IOException e, int code) {
                        if (pn == 1 && firstCached == 0) {
                            initViewsData();
                            networkFailed();
                        }
                        stopLoading();
                        if (isAdded() && !TextUtils.isEmpty(e.getMessage()))
                            showToast(e.getMessage());
                    }
                }));
    }

    void initViewsData() {
        String json = PreferenceUtil.getPreferences(context, "discoverIndex");
        if (!TextUtils.isEmpty(json)) {
            Type type = new TypeToken<List<DiscoveryIndexResponse>>() {
            }.getType();
            List<DiscoveryIndexResponse> data = new Gson().fromJson(json, type);
            datas.clear();
            gameList.clear();
            addGameTypes();
            addViewDatas(data);
            adapter.clearDownloadStatus();
            adapter.notifyDataSetChanged();
            hideSkeleton();
        } else {
            showSkeleton();
        }
    }

    private void networkFailed() {
        String json = PreferenceUtil.getPreferences(context, "discoverIndex");
        if (!NetWorkUtils.isNetworkConnected(context)
                && TextUtils.isEmpty(json))
            notNetFl.setVisibility(View.VISIBLE);
    }

    @OnClick(R.id.notNetFl)
    void notNetFl() {
        if (NetWorkUtils.isNetworkConnected(context)) {
            notNetFl.setVisibility(View.GONE);
            String json = PreferenceUtil.getPreferences(context, "discoverIndex");
            if (TextUtils.isEmpty(json)) {
                showSkeleton();
            }
            onRefresh();
        } else {
            showToast(NetConfigStr.STR_CheckNet);
        }
    }

    boolean isNull(List<DiscoveryIndexResponse> data) {
        if (data == null || data.size() == 0) return true;
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getJump_show_type() == 2
                    && data.get(i).getJump_ad_switch() == 1
                    && data.get(i) != null) {//广告位
                return false;
            } else if (data.get(i).getJump_show_type() == 1
                    && data.get(i).getGame_list() != null
                    && data.get(i).getGame_list().size() > 0
                    && data.get(i).getJump_ad_switch() == 1) {//游戏
                return false;
            }
        }
        return true;
    }

    void addViewDatas(List<DiscoveryIndexResponse> data) {
        if (data == null) return;
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getJump_show_type() == 2
                    && data.get(i).getJump_ad_switch() == 1) {//广告位
                datas.add(new ViewBean(FindFragmentAdapter.T_BILLBOARD,
                        (JumpBaseBean) data.get(i)));
            } else if (data.get(i).getJump_show_type() == 1
                    && data.get(i).getGame_list() != null
                    && data.get(i).getGame_list().size() > 0
                    && data.get(i).getJump_ad_switch() == 1) {//游戏
                if (!TextUtils.isEmpty(data.get(i).getJump_sub_title()) && data.get(i).getJump_info() != null)
                    datas.add(new ViewBean(FindFragmentAdapter.T_TITLE,
                            (JumpBaseBean) data.get(i)));
                if (data.get(i).getGame_list() != null)
                    for (int j = 0; j < data.get(i).getGame_list().size(); j++) {
                        datas.add(new ViewBean(FindFragmentAdapter.T_GAME_ITEM,
                                (GameListBaseBean) data.get(i).getGame_list().get(j)));
                        gameList.add(data.get(i).getGame_list().get(j).getGame_id());
                    }
            }
        }
    }


    private void stopLoading(boolean noMore) {
        hideSkeleton();
        if (refreshLayout!=null && refreshLayout.getLayout()!=null) {
            refreshLayout.finishRefresh();
            if (noMore)
                refreshLayout.finishLoadMoreWithNoMoreData();
            else
                refreshLayout.finishLoadMore();
        }
        adapter.clearDownloadStatus();
        adapter.notifyDataSetChanged();
    }

    private void stopLoading() {
        stopLoading(false);
    }

    public void onRefresh() {
        pn = 1;
        loadSvr();
    }

    public void onLoadMore() {
        loadSvr();
    }

    //endregion

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public static class DiscoveryType {
        int    typeId;
        int    resId;
        String name;

        public DiscoveryType(int typeId, int resId, String name) {
            this.typeId = typeId;
            this.resId = resId;
            this.name = name;
        }

        public int getTypeId() {
            return typeId;
        }

        public void setTypeId(int typeId) {
            this.typeId = typeId;
        }

        public int getResId() {
            return resId;
        }

        public void setResId(int resId) {
            this.resId = resId;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    private void changeLoginStatus() {
        recommendTopWallet.initTotalWalletNum();
    }

    //region Retrofit
    private RetrofitManager retrofitManager;
    private Retrofit        retrofit;
    private ApiUtil         api;

    void initApi() {
        if (retrofitManager == null) {
            retrofitManager = RetrofitManager.getInstance(context);
            retrofit = retrofitManager.getRetrofit();
            api = retrofit.create(ApiUtil.class);
        }
    }
    //endregion
}
